package main

import (
	"errors"
	"flag"
	"fmt"
	"os"
	"path"
	"text/tabwriter"
	"webcomics/comics"
)

var conf = flag.String("conf", "~/.comics", "Path to the config file")
var comic = flag.String("comic", "", "The name of a comic from the config file to download")
var filename = flag.String("filename", "strip", "Name with which to save comic without extension")
var all = flag.Bool("all", false, "Downloads all comics specified in 'config' and saves them into folder defined by 'filename'")
var list = flag.Bool("listing", false, "Lists all of the comics in the configuration file.")

func main() {
	flag.Parse()

	coms, err := comics.GetComics(*conf)
	if err != nil {
		fmt.Println("Can't find config file:", err)
		return
	}

	if *list {
		listComics(coms)
		return
	}

	if *all {
		downloadComics(coms)
		return
	}

	if *comic == "" {
		fmt.Println("Please define comic to download")
		return
	}

	c, ok := coms[*comic]
	if ok == false {
		fmt.Println("No comic with this name in config file at: ", conf)
		return
	}

	file, err := c.Download()
	if err != nil {
		fmt.Println("Can't download comic:", err)
		return
	}

	fn := *filename + "." + c.FileType
	makeFile(fn, file)
}

//Creates file with given name and writes given byte slice into it
func makeFile(name string, image []byte) (err error) {
	f, err := os.Create(name)
	if err != nil {
		return
	}
	_, err = f.Write(image)
	if err != nil {
		return
	}
	return
}

//Downloads all the comics in the map
func downloadComics(coms map[string]comics.Comic) {
	var folder string
	if *filename == "strip" {
		folder = "."
	} else {
		folder = *filename
	}

	errChan := make(chan error)

	for name, comic := range coms {
		go getComic(name, comic, folder, errChan)
	}

	for i := 0; i < len(coms); i++ {
		m := <-errChan
		if m != nil {
			fmt.Println(m)
		}
	}
}

//Gets comic, sending errors to the errChan channel. Sends nil if download completes succesfuly
func getComic(name string, comic comics.Comic, folder string, errChan chan error) {
	img, err := comic.Download()
	if err != nil {
		errChan <- errors.New(fmt.Sprint("Can't download ", comic.FullName, ": ", err))
		return
	}
	err = makeFile(path.Join(folder, name+"."+comic.FileType), img)
	if err != nil {
		errChan <- errors.New(fmt.Sprint("Can't write ", comic.FullName, ": ", err))
		return
	}
	errChan <- nil
}

func listComics(coms map[string]comics.Comic) {
	w := tabwriter.NewWriter(os.Stdout, 0, 8, 0, '\t', 0)
	fmt.Fprintln(w, "comic code\tcomic name")
	for name, comic := range coms {
		fmt.Fprintln(w, name, "\t", comic.FullName)
	}
	w.Flush()
}
